<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>vue3+element-plus for循环获取ref使用方法</title>
  </head>
  <body>
    <div id="app">
      <h3>vue3+element-plus for循环获取ref使用方法</h3>
      <el-row v-for="(itemForm, i) in listForms">
        <el-form :model="itemForm" :ref="el => { if (el) listFormRefs[i] = el }" :rules="rules" label-width="100px" class="demo-registerForm">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="itemForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="itemForm.password"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="removeForm(i)">移除</el-button>
      </el-row>
      <el-button @click="addForm()">添加</el-button>
      <el-button type="primary" @click="registerSubmitAll()">提交全部</el-button>
    </div>
  </body>

  <!-- 引入 Vue -->
  <!-- <script src="//unpkg.com/vue@next"></script> -->
  <script src="lib/vue/vue@3.2.9-global.js"></script>
  <!-- 引入样式 -->
  <!-- <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" /> -->
  <link rel="stylesheet" href="lib/element-ui/element-plus@1.1.0-beta.9.css" />
  <!-- 引入组件库 -->
  <!-- <script src="//unpkg.com/element-plus"></script> -->
  <script src="lib/element-ui/element-plus@1.1.0-beta.9.js"></script>
  <script>
    let app = Vue.createApp({
      mounted() {},
      setup() {
        const ref = Vue.ref;
        const reactive = Vue.reactive;
        const toRefs = Vue.toRefs;
        const onMounted = Vue.onMounted;
        const onBeforeUpdate = Vue.onBeforeUpdate;

        const listFormRefs = ref([]);
        const state = reactive({
          listForms: [{ id: 1 }],
          rules: {
            phone: [{ required: 'true', message: '账户不能为空', trigger: 'blur' }],
            password: [{ required: 'true', message: '密码不能为空', trigger: 'blur' }],
          },
        });

        // 确保在每次更新之前重置ref
        onBeforeUpdate(() => {
          console.log('onBeforeUpdate...');
          listFormRefs.value = [];
        });

        const addForm = () => {
          state.listForms.push({ id: Date.now() });
        };

        const removeForm = (i) => {
          state.listForms.splice(i, 1);
        };

        const registerSubmitAll = () => {
          console.log('registerSubmitAll 批量提交 校验 ...');
          for (let index = 0; index < state.listForms.length; index++) {
            console.log(index, state.listForms[index]);
            listFormRefs.value[index].validate((v) => {
              console.log(index, state.listForms[index], v);
            });
          }
        };

        return {
          ...toRefs(state),
          addForm,
          removeForm,
          listFormRefs,
          registerSubmitAll,
        };
      },
    });
    app.use(ElementPlus);
    app.mount('#app');
  </script>
</html>
